<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
        <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
        <title>AUI快速完成布局</title>
        <link rel="stylesheet" type="text/css" href="../../css/w3.css" />
        <link rel="stylesheet" type="text/css" href="../../css/aui.2.0.css" />
        <style type="text/css">
            body {
                background: #f0f0f0;
            }
            .bg-dark {
                background: #333333 !important;
            }
            .aui-bar-btn-item {
                background: #ffffff;
                border: none;
                border-bottom: 2px solid #ffffff;
            }
            .aui-bar-btn-item.aui-active {
                color: #039be5;
                background: #ffffff;
                border-bottom: 2px solid #039be5;
            }
            .nomore-tag {
                margin: 0 auto;
                text-align: center;
                width: auto;
                color: #333;
                padding: 20px 10px 10px 10px;
                font-size: 15px;
            }
            .title-bar {
                margin: 0 auto;
                text-align: left;
                width: auto;
                color: #333;
                padding: 3px 3px 2px 15px;
                font-size: 15px;
            }
        </style>
    </head>
    <body>
        <div class="aui-content aui-margin-b-15">
            <div class="title-bar">
                近期还贷列表
            </div>
            <ul class="aui-list aui-media-list">
                <template id="loan_list">
                    <li class="aui-list-item" id="item_container" item_index="" tapmode onclick="openLoanDetail(this)">
                        <div class="aui-media-list-item-inner">
                            <div class="aui-list-item-media" style="width: 3.2rem;">
                                <img id="company_icon" style="border-radius: 10px;" src="">
                                <div id="icon_text" class="aui-list-item-text" style="border-radius: 10px; display: none; text-align:center;"></div>
                            </div>
                            <div class="aui-list-item-inner">
                                <div class="aui-list-item-text">
                                    <div id="loan_name" class="aui-list-item-title">
                                        loan_name
                                    </div>
                                    <div id="loan_stat" class="aui-list-item-right">
                                        loan_stat
                                    </div>
                                </div>
                                <div id="loan_limit" class="aui-list-item-text aui-padded-t-10 loan_list_text" style="width: 10rem;">
                                    贷款额度
                                </div>
                            </div>
                        </div>
                        <div style="display:none; width:100%; background-color:#fff; padding: 0rem 0rem 0.5rem 0rem">
                            <div style="font-size:0.7rem; width: 18%; display:inline-block">
                                还款进度
                            </div>
                            <div style="width: 75%; display:inline-block; margin-left: 0rem">
                                <div class="progressbar-container" style="width: 100%">
                                    <div class="w3-round-xlarge" style="width: 100%; color:#000!important;background-color:#00D2F9!important">
                                        <div id="Progress3" class="w3-container w3-round-xlarge" style="important;color:#fff!important;background-color:#0092B9!important;width:0%">
                                            0%
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                    <li class="aui-info" style="padding:0.1rem 0.8rem 0.1rem 0.8rem; background-color: #f0fbff; font-size: 0.6rem">
                        <div class="aui-info-item">
                            <i class="aui-iconfont aui-icon-calendar aui-text-info"></i>
                            <span id="payDateText" class="aui-margin-l-5">还款日期：</span>
                        </div>
                    </li>
                    <li id="item_padding" class="aui-list-header" style="padding: 0.2rem; background-color: #f0f0f0;"></li>
                </template>
                <div id="list_container"></div>
            </ul>
        </div>
    </body>
    <script type="text/javascript" src="../../script/api.js" ></script>
    <script type="text/javascript" src="../../script/aui-tab.js" ></script>
    <script type="text/javascript" src="../../script/APICloud-rest-SHA1.js" ></script>
    <script type="text/javascript" src="../../script/aui-toast.js" ></script>
    <script type="text/javascript" src="../../script/aui-dialog.js" ></script>
    <script>
        var client = new Resource("A6928874653494", "4B6C428C-24C2-F9E7-3175-F983922E8C8F");
        var modelUserLoanRecord = client.Factory("userLoanRecord");
        var toast = new auiToast();
        var dialog = new auiDialog();
        var loanItemIndex;
        var company_icons = ["paipai.jpg", "dianrong.jpg", "niwodai.jpg", "zhongrongtou.jpg", "junrongdai.jpg", "caimi.jpg"];
        //var collapse = new auiCollapse({
        //	autoHide : false //是否自动隐藏已经展开的容器
        //});
        var showContent = false;
        function toggleHeader() {
            var loan_content = document.getElementById("loan_content");
            var loan_header = document.getElementById("loan_header");
            if (showContent == false) {
                loan_header.style.backgroundColor = "#f0f0f0";
                loan_content.style.display = "block";
                showContent = true;
            } else {
                loan_header.style.backgroundColor = "#f0fbff";
                loan_content.style.display = "none";
                showContent = false;
            }
        }

        function cancleAndReturn() {
            toggleHeader();
        }

        function saveAndReturn() {
            var loanInfo = {
                totalLoan : 0,
                agent : "",
                agentIndex : 0,
                loanItemId : "",
                progress : 0.0,
                loanIcon : ''
            }
            var selectAgent = document.getElementById("selectAgent");
            if (selectAgent.length == (selectAgent.selectedIndex + 1)) {
                loanInfo.agent = document.getElementById("otherAgentText").value;
                loanInfo.agentIndex = 0;
            } else {
                loanInfo.agent = selectAgent.options[selectAgent.selectedIndex].text;
                loanInfo.agentIndex = selectAgent.selectedIndex;
            }
            if (!selectAgent.selectedIndex) {
                dialog.alert({
                    title : "贷款机构未输入",
                    msg : "请重新输入 ^_^",
                    buttons : ['确定']
                });
                return;
            }
            loanInfo.totalLoan = document.getElementById("totalLoanText").value;
            if (isNaN(parseInt(loanInfo.totalLoan))) {
                dialog.alert({
                    title : "贷款数额错误",
                    msg : "请重新输入 ^_^",
                    buttons : ['确定']
                });
                return;
            }
            var payTypeIndex = 0;
            var radio = document.getElementsByName("payType");
            var radioLength = radio.length;
            for (var i = 0; i < radioLength; i++) {
                if (radio[i].checked) {
                    payTypeIndex = i;
                }
            }
            var monthPayTypeIndex = 0;
            radio = document.getElementsByName("monthPayType");
            radioLength = radio.length;
            for (var i = 0; i < radioLength; i++) {
                if (radio[i].checked) {
                    monthPayTypeIndex = i;
                }
            }
            var loanPeriodText = document.getElementById("loanPeriodText").value;
            if (isNaN(parseInt(loanPeriodText))) {
                dialog.alert({
                    title : "贷款期限错误",
                    msg : "请重新输入 ^_^",
                    buttons : ['确定']
                });
                return;
            }
            var monthRateText = document.getElementById("monthRateText").value;
            if ((payTypeIndex == 0) && isNaN(parseFloat(monthRateText))) {
                dialog.alert({
                    title : "月利率错误",
                    msg : "请重新输入 ^_^",
                    buttons : ['确定']
                });
                return;
            }
            var dayliRateText = document.getElementById("dayliRateText").value;
            if ((payTypeIndex == 1) && isNaN(parseFloat(dayliRateText))) {
                dialog.alert({
                    title : "日利率错误",
                    msg : "请重新输入 ^_^",
                    buttons : ['确定']
                });
                return;
            }
            var monthFeeRateText = document.getElementById("monthFeeRateText").value;
            if (isNaN(parseInt(monthFeeRateText))) {
                monthFeeRateText = 0;
            }
            var dayliFeeRateText = document.getElementById("dayliFeeRateText").value;
            if (isNaN(parseInt(dayliFeeRateText))) {
                dayliFeeRateText = 0;
            }
            var serviceRateText = document.getElementById("serviceRateText").value;
            if (isNaN(parseInt(loanPeriodText))) {
                serviceRateText = 0;
            }
            var oneTimeRateText = document.getElementById("oneTimeRateText").value;
            if (isNaN(parseFloat(loanPeriodText))) {
                oneTimeRateText = 0
            }
            var selectYear = document.getElementById("selectYear").value;
            if (isNaN(parseInt(selectYear))) {
                dialog.alert({
                    title : "年份未选择",
                    msg : "请重新输入 ^_^",
                    buttons : ['确定']
                });
                return;
            }
            var selectMonth = document.getElementById("selectMonth").value;
            if (isNaN(parseInt(selectMonth))) {
                dialog.alert({
                    title : "月份未选择",
                    msg : "请重新输入 ^_^",
                    buttons : ['确定']
                });
                return;
            }
            var selectDay = document.getElementById("selectDay").value;
            if (isNaN(parseInt(selectDay))) {
                dialog.alert({
                    title : "日期未选择",
                    msg : "请重新输入 ^_^",
                    buttons : ['确定']
                });
                return;
            }
            toast.loading({
                title : "保存中",
                duration : 2000
            }, function(ret) {
                console.log(ret);
                setTimeout(function() {
                    toast.hide();
                }, 30000)
            });
            loanInfo.loanIcon = '../../image/company_icon/' + company_icons[selectAgent.selectedIndex - 1];
            modelUserLoanRecord.save({
                "userId" : $api.getStorage('userID'),
                "username" : $api.getStorage('username'),
                "finInstName" : loanInfo.agent,
                "finInstIndex" : loanInfo.agentIndex,
                "loanAmount" : loanInfo.totalLoan,
                "payTypeIndex" : payTypeIndex,
                "monthlyPayTypeIndex" : monthPayTypeIndex,
                "loanPeriod" : loanPeriodText,
                "monthRate" : monthRateText,
                "dayRate" : dayliRateText,
                "monthFeeRate" : monthFeeRateText,
                "dayFeeRate" : dayliFeeRateText,
                "oneTimeRate" : oneTimeRateText,
                "otherExpense" : serviceRateText,
                "validYear" : selectYear,
                "validMonth" : selectMonth,
                "validDay" : selectDay,
                "loanItemIconName" : loanInfo.loanIcon,
                "payProgress" : 20
            }, function(ret, err) {
                if (err) {
                    //处理错误 err
                } else {
                    //处理数据 ret
                    //alert(JSON.stringify(ret));
                    toast.hide();
                    toast.success({
                        title : "保存成功！",
                        duration : 1000
                    });
                    loanInfo.loanItemId = ret.id;
                    loanInfo.progress = calcPayProgress(ret);
                    addLoanListItem(loanInfo);
                    toggleHeader();
                }
            })
        }

        function checkAgent() {
            var agent = document.getElementById("selectAgent");
            //定位id
            var index = agent.selectedIndex;
            if (index == 0) {
                agent.style.color = "#989898"
            } else {
                agent.style.color = "#000"
            }
            // 选中索引
            var otherAgent = document.getElementById("otherAgent");
            if (agent.length == (index + 1)) {
                otherAgent.style.display = "block";
            } else {
                otherAgent.style.display = "none";
            }
        }

        function checkYear() {
            var agent = document.getElementById("selectYear");
            var yearWrap = document.getElementById("yearWrap");
            //定位id
            var index = agent.selectedIndex;
            if (index == 0) {
                agent.style.color = "#989898"
            } else {
                agent.style.color = "#000"
                yearWrap.style.width = "15%";
            }
        }

        function checkMonth() {
            var agent = document.getElementById("selectMonth");
            var monthWrap = document.getElementById("monthWrap");
            //定位id
            var index = agent.selectedIndex;
            if (index == 0) {
                agent.style.color = "#989898"
            } else {
                agent.style.color = "#000";
                monthWrap.style.width = "10%";
            }
        }

        function checkDay() {
            var agent = document.getElementById("selectDay");
            var dayWrap = document.getElementById("dayWrap");
            //定位id
            var index = agent.selectedIndex;
            if (index == 0) {
                agent.style.color = "#989898"
            } else {
                agent.style.color = "#000";
                dayWrap.style.width = "10%";
            }
        }

        function changePayType() {
            var radio = document.getElementsByName("payType");
            var radioLength = radio.length;
            for (var i = 0; i < radioLength; i++) {
                if (radio[i].checked) {
                    var monthRate = document.getElementById("monthRate");
                    var dayliRate = document.getElementById("dayliRate");
                    var monthFeeRate = document.getElementById("monthFeeRate");
                    var dayliFeeRate = document.getElementById("dayliFeeRate");
                    var monthPayMode = document.getElementById("monthPayMode");
                    var loanPeriodLabel = document.getElementById("loanPeriodLabel");
                    if (i == 0) {
                        monthRate.style.display = "block";
                        dayliRate.style.display = "none";
                        monthFeeRate.style.display = "block";
                        dayliFeeRate.style.display = "none";
                        monthPayMode.style.display = "block";
                        loanPeriodLabel.textContent = "借款总期限(月)：";
                    } else {
                        monthRate.style.display = "none";
                        dayliRate.style.display = "block";
                        monthFeeRate.style.display = "none";
                        dayliFeeRate.style.display = "block";
                        monthPayMode.style.display = "none";
                        loanPeriodLabel.textContent = "借款总期限(天)：";
                    }
                }
            }
        }

        function checkRecentPay(loanListItem) {
            var alertRequired = 0;
            var myDate = new Date();
            var year = parseInt(myDate.getFullYear());
            var month = parseInt(myDate.getMonth()) + 1;
            var day = parseInt(myDate.getDate());
            var oldYear = parseInt(loanListItem.validYear);
            var oldMonth = parseInt(loanListItem.validMonth);
            var oldDay = parseInt(loanListItem.validDay);
            //alert("day: " + day + " oldDay: " + oldDay);
            var dayDiff = oldDay - day;
            if (loanListItem.payTypeIndex == 1) {
                var curDayCount = year * 365 + (month - 1) * 30 + day;
                var payDayCount = oldYear * 365 + (oldMonth - 1) * 30 + oldDay;
                var countDiff = payDayCount - curDayCount;
                if (countDiff > 0 && countDiff < 5) {
                    alertRequired = 1;
                    //alert(count);
                }
            } else {
                if (dayDiff > 0 && dayDiff < 5) {
                    alertRequired = 1;
                    //alert(count);
                }
            }
            return alertRequired;
        }

        function calcPayProgress(e) {
            var myDate = new Date();
            var year = parseInt(myDate.getFullYear());
            var month = parseInt(myDate.getMonth()) + 1;
            var day = parseInt(myDate.getDate());
            var oldYear = parseInt(e.validYear);
            var oldMonth = parseInt(e.validMonth);
            var oldDay = parseInt(e.validDay);
            if (e.payTypeIndex == 1) {
                var curDayCount = year * 365 + (month - 1) * 30 + day;
                var payDayCount = oldYear * 365 + (oldMonth - 1) * 30 + oldDay;
                if (curDayCount > payDayCount) {
                    return 100.00;
                } else {
                    return 0;
                }
            } else {
                var payMonth = 0;
                yearDiff = year - oldYear;
                if (yearDiff > 0) {
                    payMonth = (yearDiff - 1) * 12 + (12 - oldMonth + 1) + (month - 1);
                } else if (yearDiff == 0) {
                    monthDiff = month - oldMonth;
                    if (monthDiff > 0) {
                        payMonth = monthDiff;
                    } else if (monthDiff < 0) {
                        return 0;
                    }
                } else if (yearDiff < 0) {
                    return 0;
                }
                if (day > oldDay) {
                    payMonth = payMonth + 1;
                }
                var PayRate = payMonth * 100.00 / e.loanPeriod;
                if (PayRate > 100.00) {
                    PayRate = 100.00;
                }
                return PayRate;
            }
            //alert("Date: " + oldYear + " " + oldMonth + " " + oldDay);
        }

        function loadLoanList() {
            var index_start = 0;
            var end = 5;
            var loan_names = ["拍拍贷", "点融网", "你我贷", "中融投", "君融贷", "才米公社"];
            var loan_stats = [10.00, 10.13, 20.62, 10.78, 10.36, 10.72];
            var loan_limits = ["10000", "1000", "10000", "5000", "10000", "1000"];
            var loan_descs = ["10天快速放贷 仅需央行征信证明+身份证", "仅需身份证+芝麻信用，24小时快速放贷", '获政府认可金融平台 可投活期', '中国互联网金融协会常务理事单位', '永诚保险保障 注册再送100元微信红包', '花旗融资担保 资金独立保管'];
            var company_icons = ["paipai.jpg", "dianrong.jpg", "niwodai.jpg", "zhongrongtou.jpg", "junrongdai.jpg", "caimi.jpg"];
            var loanList = [];
            toast.loading({
                title : "加载中",
                duration : 2000
            }, function(ret) {
                console.log(ret);
                setTimeout(function() {
                    toast.hide();
                }, 30000)
            });
            //alert($api.getStorage('userID'));
            modelUserLoanRecord.query({
                filter : {
                    "limit" : 50,
                    "order" : "createdAt DESC",
                    "where" : {
                        "userId" : $api.getStorage('userID'),
                        //"alertRequired" : 1
                    }
                }
            }, function(ret, err) {
                if (err) {
                    //处理错误 err
                    alert(JSON.stringify(err));
                } else {
                    //处理数据 ret
                    loanList = ret;
                    //alert(JSON.stringify(ret));
                    for (var i = 0; i < loanList.length; i++) {
                        var alertRequired = 0;
                        var calcRate = calcPayProgress(loanList[i]);
                        if (calcRate < 100.00) {
                            if (checkRecentPay(loanList[i]) != 1) {
                                continue;
                            }
                        } else {
                            continue;
                        }
                        var template = document.querySelector('#loan_list');
                        var clone = template.content.cloneNode(true);
                        var icon = clone.querySelector('#company_icon');
                        if (loanList[i].finInstIndex) {
                            icon.src = loanList[i].loanItemIconName;
                        } else {
                            icon.style.display = 'none';
                            var iconText = clone.querySelector('#icon_text');
                            iconText.style.display = 'inline-block';
                            iconText.textContent = loanList[i].finInstName.substring(0, 1);
                            iconText.style.fontSize = '1.7rem';
                            iconText.style.width = '3.2rem';
                            iconText.style.height = '2.4rem';
                            iconText.style.color = '#fff';
                            iconText.style.backgroundColor = '#039be5';
                        }
                        var loan_name = clone.querySelector('#loan_name');
                        loan_name.textContent = loanList[i].finInstName;
                        var loan_stat = clone.querySelector('#loan_stat');
                        var calcRate = calcPayProgress(loanList[i]);
                        //alert("rate: " + calcRate);
                        loan_stat.textContent = '还款进度:' + calcRate.toFixed(2) + '%';
                        var loan_limit = clone.querySelector('#loan_limit');
                        loan_limit.textContent = '贷款数额:' + loanList[i].loanAmount + '元';
                        var payDateText = clone.querySelector('#payDateText');
                        if (loanList[i].payTypeIndex == 0) {
                            var myDate = new Date();
                            var year = parseInt(myDate.getFullYear());
                            var month = parseInt(myDate.getMonth()) + 1;
                            payDateText.textContent = '还款日期: ' + year + ' 年 ' + month + ' 月 ' + loanList[i].validDay + ' 日';
                        } else if (loanList[i].payTypeIndex == 1) {
                            payDateText.textContent = '还款日期: ' + loanList[i].validYear + ' 年 ' + loanList[i].validMonth + ' 月 ' + loanList[i].validDay + ' 日';
                        }
                        var item_container = clone.querySelector('#item_container');
                        item_container.item_index = loanList[i].id;
                        var list_container = document.querySelector('#list_container');
                        list_container.appendChild(clone);
                    };
                    toast.hide();
                }
            });
        }

        function addLoanListItem(loanInfo) {
            var loan_name = loanInfo.agent;
            var loan_stat = loanInfo.progress;
            var loan_limit = loanInfo.totalLoan;
            var template = document.querySelector('#loan_list');
            var clone = template.content.cloneNode(true);
            var company_icons = ["paipai.jpg", "dianrong.jpg", "niwodai.jpg", "zhongrongtou.jpg", "junrongdai.jpg", "caimi.jpg"];
            var agent = document.getElementById("selectAgent");
            var icon = clone.querySelector('#company_icon');
            if (loanInfo.agentIndex) {
                icon.src = loanInfo.loanIcon;
            } else {
                icon.style.display = 'none';
                var iconText = clone.querySelector('#icon_text');
                iconText.style.display = 'inline-block';
                iconText.textContent = loanInfo.agent.substring(0, 1);
                iconText.style.fontSize = '1.7rem';
                iconText.style.width = '3.2rem';
                iconText.style.height = '2.4rem';
                iconText.style.color = '#fff';
                iconText.style.backgroundColor = '#039be5';
            }
            var loan_name_element = clone.querySelector('#loan_name');
            loan_name_element.textContent = loan_name;
            var loan_stat_element = clone.querySelector('#loan_stat');
            loan_stat_element.textContent = '还款进度:' + loan_stat.toFixed(2) + '%';
            var loan_limit_element = clone.querySelector('#loan_limit');
            loan_limit_element.textContent = '贷款数额:' + loan_limit + '元';
            var item_container_element = clone.querySelector('#item_container');
            item_container_element.item_index = loanInfo.loanItemId;
            var list_container = document.querySelector('#list_container');
            list_container.insertBefore(clone, list_container.childNodes[0]);
            //appendChild(clone);
        }

        function openLoanDetail(e) {
            var options = {
                index : e.item_index,
            };
            var delay = 0;
            if (api.systemType != 'ios') {
                delay = 300;
            }
            api.openWin({
                name : 'my_loan_win',
                url : './my_loan_win.html',
                bounces : false,
                delay : delay,
                slidBackEnabled : true,
                vScrollBarEnabled : false,
                animation : {
                    type : "movein", //动画类型（详见动画类型常量）
                    subType : "from_left", //动画子类型（详见动画子类型常量）
                    duration : delay //动画过渡时间，默认300毫秒
                },
                pageParam : options,
            });
        }

        function clearList() {
            var list_container = document.querySelector('#list_container');
            var children = list_container.childNodes;
            var childnum = children.length;
            for (var j = 0; j < childnum; j++) {
                list_container.removeChild(list_container.firstChild);
            }
        }

        apiready = function() {
            api.setRefreshHeaderInfo({
                visible : true,
                bgColor : '#ccc',
                textColor : '#fff',
                textDown : '下拉刷新...',
                textUp : '松开刷新...',
                showTime : true
            }, function(ret, err) {
                clearList();
                loadLoanList();
                api.refreshHeaderLoadDone();
            });
            api.parseTapmode();
            loadLoanList();
            api.addEventListener({
                name : 'ev_deleteLoanItem'
            }, function(ret, err) {
                /*
                 var nodeToDels = document.querySelectorAll("#item_container");
                 var item_paddings = document.querySelectorAll("#item_padding");
                 for (var i = 0; i < nodeToDels.length; i++) {
                 if (nodeToDels[i].item_index == ret.value.index) {
                 nodeToDels[i].parentNode.removeChild(nodeToDels[i]);
                 item_paddings[i].parentNode.removeChild(item_paddings[i]);
                 }
                 }*/
                api.closeWin({
                    name : 'my_loan_win',
                });
                clearList();
                loadLoanList();
            });
            //alert($api.getStorage('userID'));
        }
    </script>
</html>